/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 - 2008 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/

package com.genia.toolbox.web.gwt.form.client.process;

import java.util.List;

import com.genia.toolbox.web.gwt.form.client.form.SortableMultipleItem;
import com.genia.toolbox.web.gwt.form.client.widget.SortableVerticalPanel;
import com.genia.toolbox.web.gwt.form.client.widget.SortableWidget;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * class to help sorting elements.
 */
public class ProcessSortable
{
  /**
   * move the given value to the given position.
   * 
   * @param <TYPE>
   *          the type of the elemenst if the list
   * @param list
   *          the {@link List} to modify
   * @param oldIndex
   *          the index of the value to move
   * @param newIndex
   *          the index of the final destination of the value
   */
  public static <TYPE> void move(List<TYPE> list, int oldIndex, int newIndex)
  {
    int size = list.size();
    if (oldIndex < 0 || newIndex < 0 || oldIndex >= size || newIndex >= size || oldIndex == newIndex) {
      return;
    }
    TYPE formManager = list.remove(oldIndex);
    list.add(newIndex, formManager);

  }



  /**
   * returns a {@link VerticalPanel} suited to the given {@link SortableWidget}.
   * 
   * @param sortableWidget
   *          the {@link SortableWidget} to retrieve a {@link VerticalPanel} for
   * @return a {@link VerticalPanel} suited to the given {@link SortableWidget}
   */
  public static VerticalPanel getVerticalPanel(SortableWidget sortableWidget)
  {
    if (sortableWidget.getItem() instanceof SortableMultipleItem && ((SortableMultipleItem) sortableWidget.getItem()).isSortable()) {
      return new SortableVerticalPanel(sortableWidget);
    }
    else {
      return new VerticalPanel();
    }
  }
}
